<template>
    <div class="content">
        <div class="top">
            <ul>
                <li>
                    <TextIpt>
                        <p>活动名称</p>
                    </TextIpt>
                </li>
                <li>
                    <SelectIpt>
                        <p>报名状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt>
                        <p>活动状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <SelectIpt>
                        <p> 审核状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <BlueBtn>查询</BlueBtn>
                </li>
                <li>
                    <BlueBtn @click.native="add">新增</BlueBtn>
                </li>
            </ul>
        </div>
        <div class="table">

            <el-table :data="filterData.slice(pages, pages + 8)" border style="width: 100%">
                <el-table-column prop="ActivityName" label="活动名称" width="180">
                </el-table-column>
                <el-table-column prop="EnrollDate" label="报名时间" width="240">
                </el-table-column>
                <el-table-column prop="Population" label="人数限制" width="90">
                </el-table-column>
                <el-table-column label="已报名人数" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.SignUp == null ? '--' : scope.row.SignUp }}
                    </template>
                </el-table-column>
                <el-table-column prop="CreateMan" label="创建人" width="160">
                </el-table-column>
                <el-table-column prop="CreateDate" label="创建时间" width="180">
                </el-table-column>
                <el-table-column prop="AuditMan" label="审核人" width="100">
                </el-table-column>
                <el-table-column prop="AuditState" label="审核状态" width="100">
                </el-table-column>
                <el-table-column label="报名状态" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.EnrollState == null ? '--' : scope.row.EnrollState }}
                    </template>
                </el-table-column>
                <el-table-column label="活动状态" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.ActiveState == null ? '--' : scope.row.ActiveState }}

                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.EnrollState == '报名中'" size="mini"
                            @click="stops(scope.$index, scope.row)">终止报名</el-button>
                        <el-button v-if="scope.row.AuditState == '待审核'" size="mini"
                            @click="audit(scope.$index, scope.row)">审核</el-button>
                        <el-button size="mini" v-if="scope.row.AuditState == '已通过'"
                            @click="edit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="page">
                <div class="total-page">
                    <p>共<span>{{ Math.ceil(filterData.length / 8) }}</span>页/<span>{{ filterData.length }}</span>条数据
                    </p>
                </div>
                <el-pagination background layout="prev, pager, next,jumper" @current-change="getPage" :page-size=8
                    :current-page.sync=page :total="filterData.length" hide-on-single-page>
                </el-pagination>
            </div>
        </div>
        <!-- 新增对话框 -->
        <el-dialog title="提示" :visible.sync="addDialog" width="30%" :before-close="addClose" class="addDialog">
            <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
                <el-form-item label="活动名称" prop="activeName">
                    <el-input v-model="addForm.activeName"></el-input>
                </el-form-item>
                <el-form-item label="人数限制" prop="activeNum">
                    <el-input v-model="addForm.activeNum"></el-input>
                </el-form-item>
                <el-form-item label="报名时间" prop="date">
                    <el-date-picker v-model="addForm.date" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 点击编辑对话框 -->
        <el-dialog title="编辑" :visible.sync="editDialog" width="30%" :before-close="addClose" class="editDialog">
            <el-form ref="editForm" :model="editForm" label-width="80px">
                <el-form-item label="活动名称">
                    <el-input v-model="editForm.activeName"></el-input>
                </el-form-item>
                <el-form-item label="活动状态">
                    <el-select v-model="editForm.activeState" placeholder="请选择活动区域">
                        <el-option value="未开始"></el-option>
                        <el-option value="进行中"></el-option>
                        <el-option value="已结束"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editConfrim('editForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BlueBtn from '@/components/BlueBtn.vue';
import SelectIpt from '@/components/SelectIpt.vue';
import TextIpt from '@/components/TextIpt.vue';
export default {
    components: {
        BlueBtn,
        SelectIpt,
        TextIpt
    },
    data() {
        return {
            editForm: {
                activeName: '',
                activeState: '',
                id: '',
                index: "",
            },
            editDialog: false,
            page: 0,
            pages: 0,
            allData: [],
            filterData: [],
            addDialog: false,
            addForm: {
                activeName: '',
                activeNum: "",
                date: "",
            },
            rules: {
                activeName: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                ],
                activeNum: [
                    { required: true, message: '请输入报名人数', trigger: 'blur' },
                ],
                date: [
                    { required: true, message: '请选择报名时间', trigger: 'blur' },
                ],
            }
        }
    },
    methods: {
        updateActiveState() {
            this.$axios.post('http://127.0.0.1/active/updateActiveState', {
                ...this.editForm
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.editDialog = false
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });

            }).catch(err => {
                console.log(err);
            })
        },
        edit(index, row) {
            this.editForm.activeName = row.ActivityName
            this.editForm.activeState = row.ActiveState
            this.editForm.id = row.ID
            this.editForm.index = index + this.pages
            this.editDialog = true
        },
        updateAuditState(id) {
            this.$axios.post('http://127.0.0.1/active/updateAuditState', {
                id
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.getAllData()
                this.addDialog = false
                this.$message({
                    type: 'success',
                    message: '添加成功!'
                });

            }).catch(err => {
                console.log(err);
            })
        },
        audit(index, row) {
            this.$confirm('此操作将通过审核, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.filterData[index + this.pages].AuditState = '已通过'
                this.filterData[index + this.pages].EnrollState = '未发布'
                this.updateAuditState(row.ID)
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        add() {
            this.addDialog = true
        },
        addActive() {
            this.$axios.post('http://127.0.0.1/active/addActive', {
                ...this.addForm,
                addMan: localStorage.getItem('name')
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.getAllData()
                this.addDialog = false
                this.$message({
                    type: 'success',
                    message: '添加成功!'
                });

            }).catch(err => {
                console.log(err);
            })
        },
        formatDate(dateStr) {
            // 创建 Date 对象
            const date = new Date(dateStr);

            // 获取年、月、日、小时、分钟（使用本地时区）
            const year = date.getFullYear(); // 本地时间的年份
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            const minute = String(date.getMinutes()).padStart(2, '0');

            // 格式化为 "YYYY-MM-DD HH:MM"
            return `${year}-${month}-${day} ${hour}:${minute}`;
        },
        editConfrim(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let flag = false
                    if (this.filterData[this.editForm.index].ActivityName != this.editForm.activeName) {
                        this.filterData[this.editForm.index].ActivityName = this.editForm.activeName
                        flag = true
                    }

                    if (this.filterData[this.editForm.index].ActiveState != this.editForm.activeState) {
                        this.filterData[this.editForm.index].ActiveState = this.editForm.activeState
                        flag = true
                    }
                    if (flag) {
                        this.updateActiveState()
                        return
                    }
                    this.editDialog = false

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.addForm.date[0] = this.formatDate(this.addForm.date[0])
                    this.addForm.date[1] = this.formatDate(this.addForm.date[1])
                    this.addActive()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addClose() {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.addDialog = false
                    this.editDialog = false
                })
                .catch(_ => { });
        },
        //修改报名状态
        updateEnrollState(id, str) {
            this.$axios.post('http://127.0.0.1/active/updateEnrollState', {
                id,
                str
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {

            }).catch(err => {
                console.log(err);
            })
        },
        stops(index, row) {
            this.$confirm('  确定要直接终止报名嘛，终止后社区未报名用户将无法报名活动，请谨慎操作！', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.filterData[index + this.pages].EnrollState = '报名结束'
                this.updateEnrollState(row.ID, '报名结束')
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });
        },
        //get 当前页
        getPage(page) {
            this.pages = 8 * (page - 1)
        },
        getAllData() {
            this.$axios.get('http://127.0.0.1/active/all', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.allData = res.data
                this.filterData = res.data
            }).catch(err => {
                console.log(err);
            })
        }
    },
    mounted() {
        this.getAllData()
    }
}
</script>

<style scoped>
.editDialog>>>.el-input {
    width: 200px;
}

.addDialog>>>.el-input:nth-child(1) {
    width: 200px;
}

.addDialog>>>.el-input {
    width: 360px;
}

.addDialog>>>.el-range-separator {
    padding: 0;
}

.table>>>.el-table {
    min-height: 615px;
}

.page {
    display: flex;
    align-items: center;
    justify-content: end;
    margin-top: 20px;
}

.page>>>button {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    background: #fff !important;
}

.page>>>.active {
    border-color: rgba(26, 135, 254, 1) !important;
    background-color: rgba(26, 135, 254, 1) !important;
    color: #fff !important;
}

.page>>>.el-pager li {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    font-size: 12px;
    color: #999;
    font-weight: normal !important;
    background: #fff;
}

.total-page span {
    color: #FF3C2C;
}

.total-page {
    font-size: 12px;
    color: #666;
}

.table {
    padding: 20px 20px 50px;
    background: #fff;
    border-radius: 4px;
    margin-top: 10px;
}

.top ul {
    display: flex;
    white-space: nowrap;
    font-size: 13px;
    color: #666;
}

.top {
    background: #fff;
    padding: 20px 35px;
    border-radius: 4px;
}

.top li {
    margin-right: 50px;
}
</style>